from flask import (
    request, json, current_app
)
# serializer for JWT
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
# exceptions for JWT
from itsdangerous import SignatureExpired, BadSignature, BadData
import time
class Auth():
    openid = None
    def __init__(self,openid):
        self.openid = openid

    def genTokenSeq(self, expires,openid):
        s = Serializer(
            secrect_key = current_app.config.get('SECRET_KEY'),
            salt=current_app.config.get['AUTH_SALT'],
            expires_in=expires
        )
        timestamp = time.time()
        return s.dumps({
            'openid':openid ,
             'iat':timestamp
        })

    def tokenAuth(self,token):
        s = Serializer(
            secret_key=current_app.config.get['SECRET_KEY'],
            salt=current_app.config.get['AUTH_SALT'])
        try:
            data = s.loads(token)
        except SignatureExpired:
            msg = 'token expired'
            current_app.logger.warning(msg)
            return [None, msg]
        except BadSignature as e:
            encoded_payload = e.payload
            if encoded_payload is not None:
                try:
                    s.load_payload(encoded_payload)
                except BadData:
                    # the token is tampered.
                    msg = 'token tampered'
                    current_app.config.get.logger.warning(msg)
                    return [None, None, msg]
            msg = 'badSignature of token'
            print(msg)
            return [None, None, msg]
        except:
            msg = 'wrong token with unknown reason'
            print(msg)
            return [None, None, msg]
        if ('openid' not in data):
            msg = 'illegal payload inside'
            print(msg)
            return [None, None, msg]
        msg = 'user(' + data['openid'] + ') logged in by token.'
        #        app.logger.info(msg)
        openid = data['openid']
        return [openid, msg]
